import env from '../config/env';
import message from './message';
var QQMapWX = require('./qqmap-wx-jssdk.min');
var qqmapsdk = new QQMapWX({
	key: env.mapKey
});
var municipality = ['重庆市', '北京市', '上海市', '天津市']; //直辖市
var cqMainDistrict = ['渝北区', '江北区', '渝中区', '南岸区', '九龙坡区', '巴南区', '大渡口区', '沙坪坝区', '北碚区']; //重庆主城9区

function handleAddress(result) {
	result.gyyx_current_position = {
		latitude: result.result.location.lat,
		longitude: result.result.location.lng,
		cityCode: result.result.ad_info.city_code.replace(result.result.ad_info.nation_code, ''),
		province: result.result.address_component.province,
		city: result.result.address_component.city,
		show_name: ''
	};
	for (let item of municipality) {
		if (item == result.result.address_component.province) {
			if (item == '重庆市') {
				result.gyyx_current_position.city = '重庆郊县';
				result.gyyx_current_position.show_name = '重庆郊县';
				result.gyyx_current_position.cityCode = '500200';
				for (let district of cqMainDistrict) {
					if (district == result.result.address_component.district) {
						result.gyyx_current_position.city = '重庆城区';
						result.gyyx_current_position.show_name = '重庆城区';
						result.gyyx_current_position.cityCode = '500100';
						break;
					}
				}
			} else {
				result.gyyx_current_position.show_name = result.result.address_component.province + result.result
					.address_component.province.replace('市', '城区');
				result.gyyx_current_position.cityCode = Number(result.gyyx_current_position.cityCode) + 100 + '';
			}
			break;
		}
	}
	if (!result.gyyx_current_position.show_name) {
		result.gyyx_current_position.show_name = result.result.address_component.province + result.result
			.address_component.city;
	}
	return result;
}

/**
 *
 * @param {地址坐标对象} location
 * @param {回调函数} fn
 */

const reverseGeocoder = (location, fn) => {
	qqmapsdk.reverseGeocoder({
		location: location,
		get_poi: 1,
		success: (res) => {
			if (res.status == 0) {
				if (fn) {
					fn(handleAddress(res));
				}
			} else {
				message.toast(res.message);
			}
		},
		fail: (err) => {
			console.log('逆转坐标点错误：', err);
		}
	});
};
/**
 * 获取当前位置
 */
const getCurrentPosition = (fn) => {
	uni.getLocation({
		type: 'gcj02',
		//返回可以用于wx.openLocation的经纬度
		success: (res) => {
			const latitude = res.latitude;
			const longitude = res.longitude;
			qqmapsdk.reverseGeocoder({
				location: {
					latitude,
					longitude
				},
				// location: {
				//   latitude: 31.183235,
				//   longitude: 121.459159
				// },
				get_poi: 1,
				success: (result) => {
					if (result.status == 0) {
						if (fn) {
							fn(handleAddress(result));
						}
					} else {
						message.toast(result.message);
					}
				},
				fail: (err) => {
					console.log('逆转坐标点错误：', err);
				}
			});
		},
		fail: (err) => {
			console.log('获取当前定位错误:', err);
			uni.showModal({
				title: '获取定位权限失败',
				content: '获取定位权限失败，如需使用打卡功能，请先开启定位授权',
				confirmText: '去设置',
				complete: (res) => {
					if (res.confirm) {
						uni.openSetting({
							success: (res) => {
								console.log(res);
							}
						});
					}
				}
			});
		}
	});
};
const mapSearch = (keyword, location, fn) => {
	qqmapsdk.search({
		keyword,
		location,
		page_size: 20,
		success: (res) => {
			if (res.status == 0) {
				if (fn) {
					fn(res);
				}
			} else {
				message.toast(res.message);
			}
		},
		fail: (err) => {
			message.toast('搜索失败:', err);
			console.log('搜索失败：', err);
		}
	});
};

function haversine(lat1, lon1, lat2, lon2) {
	const R = 6371000; // 地球平均半径，单位为米
	const dLat = ((lat2 - lat1) * Math.PI) / 180;
	const dLon = ((lon2 - lon1) * Math.PI) / 180;
	const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos((lat1 * Math.PI) / 180) * Math.cos((lat2 * Math.PI) /
		180) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
	const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
	const distance = R * c;
	return distance;
}
const isInsideCircle = (centerLat, centerLon, radius, pointLat, pointLon) => {
	const distance = haversine(centerLat, centerLon, pointLat, pointLon);
	return distance <= radius;
};
const computeDistance = (lat1, lon1, lat2, lon2) => {
	return haversine(lat1, lon1, lat2, lon2);
};
export {
	reverseGeocoder,
	isInsideCircle,
	computeDistance,
	getCurrentPosition,
	mapSearch
};